<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
// 引入excel组件
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
// 批量导入的请求
import { addEmployeeExcel } from '@/api/employees'
import { formatExcelDate } from '@/utils/index'
export default {
  name: 'Import',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    handleDownload() {
      this.downloadLoading = true
      //  import('@/vendor/Export2Excel') 懒加载的方式导入一个模块(文件)
      import('@/vendor/Export2Excel').then(excel => {
        // excel 指的是模块对象 , 可以使用excel 调用@/vendor/Export2Excel这个文件中的文件属性
        // excel.export_json_to_excel
        const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    // 将英文转化为中文
    formatDate(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      // 如果list中有数组,才需要生成表头
      if (!one) return
      const header = Object.keys(one).map(enkey => {
        return map[enkey]
      })
      // 2. 生成data数据
      const data = list.map(item => {
        return Object.values(item)
      })
      return { header: header, data: data }
    },

    // 上传文件大小之前的回调函数
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 1. 将excel文件中的数据读取出来转化为js数据
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      console.log('results', results)
      console.log('header', header)
      // 将excel 读取出来的数据进行格式化处理(将中文转英文)
      const data = this.transToExcel(results)
      console.log(data)
      this.doAdd(data)
    },
    // 实现批量导入
    async doAdd(data) {
      try {
        const res = await addEmployeeExcel(data)
        console.log('addEmployeeExcel', res)
        // 保存数据
        // 回到之前的页面
        this.$router.back() // back是返回上一页的方法
      } catch (err) {
        console.log('addEmployeeExcel', err)
      }
    },
    // 将中文转化为英文
    transToExcel(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      const result = data.map(zhObj => {
        const zhkeys = Object.keys(zhObj)
        const enkeyObj = {}
        zhkeys.forEach(zhkey => {
          const enkey = mapInfo[zhkey]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            enkeyObj[enkey] = formatExcelDate(zhObj[zhkey])
          } else {
            enkeyObj[enkey] = zhObj[zhkey]
          }
        })
        return enkeyObj
      })

      return result
    }
  }
}
</script>
